from flask import current_app, jsonify, session, g
from info.utils.response_code import RET

import functools


# 自定义过滤器
def set_rank_class(index):
    # 根据传入的下标返回不同的样式字符串
    if index == 1:
        return "first"
    elif index == 2:
        return "second"
    elif index == 3:
        return "third"
    else:
        return ""


# g对象,能够零时保存本次请求的内容
# 查询登陆用户的装饰器
def user_login_data(view_func):
    @functools.wraps(view_func)
    def wrapper(*args, **kwargs):
        # 1.实现要装饰的功能
        # 查询当前登陆用户的user_id
        user_id = session.get("user_id")
        # 1.2 根据user_id查询user对象
        from info.models import User
        user = None
        if user_id:
            try:
                user = User.query.filter(User.id == user_id).first()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="用户数据查询异常")
        g.user = user
        # 2.执行原函数
        return view_func(*args, **kwargs)
    return wrapper









